package com.jinkaimen.kqb.ui.activity.addmerchant;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.activity.SelectListActivity;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.bean.AuUserBean;
import com.jinkaimen.kqb.bean.BizShopBean;
import com.jinkaimen.kqb.bean.KeyAndValueBean;
import com.jinkaimen.kqb.bean.ReportRegisterGetBean;
import com.jinkaimen.kqb.bean.SearchShopBean;
import com.jinkaimen.kqb.constant.ConstantPool;
import com.jinkaimen.kqb.manager.ApiManager;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import retrofit2.Call;
import retrofit2.Response;

public class RegisterAddActivity extends BaseActivity {

    private static final int REQUEST_CODE_SETTLE_TYPE = 0;
    private EditText mTelView;
    private List<KeyAndValueBean> mSettleTypeList;
    private ArrayList<String> mSettleTypeStringList = new ArrayList<>();
    private int mDefaultIndex = -1;
    private TextView mSettleTypeView;
    private EditText mShopNameView;
    private long mUserId;
    private boolean canEdit;
    private long mShopId;
    private String industryCode;
    private TextView mNextButton;
    private RelativeLayout rl_activity_register_industory;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {

    }

    @Override
    protected void initIntentData(Intent callIntent) {
        mUserId = callIntent.getLongExtra("report_account_id", 0);
        canEdit = callIntent.getBooleanExtra("canEdit", true);
        mShopId = callIntent.getLongExtra("report_shop_id", 0);
//        mUserId = callIntent.getLongExtra("report_user_id", 0);
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_register;
    }

    @Override
    protected void initChildView() {
        if (canEdit) {
            mTitleBarView
                    .setTitleText("填写商铺资料");//
        } else {
            mTitleBarView.setTitleText("商铺资料")
                    .addActions(
                            new TitleBarView.Action("下一步") {
                                @Override
                                public void performAction(View view) {
                                    Bundle bundle = new Bundle();
                                    bundle.putBoolean("canEdit", canEdit);
                                    bundle.putLong("report_account_id", mUserId);
                                    bundle.putLong("report_shop_id", mShopId);
                                    ActivityUtils.startActivityAndFinish(RegisterAddActivity.this, IdentificationShopStep1Activity.class, bundle);
                                }
                            }
                    );
        }
        mShopNameView = (EditText) findViewById(R.id.et_activity_register_shop_name);
        mSettleTypeView = (TextView) findViewById(R.id.tv_activity_register_industory);
        mTelView = (EditText) findViewById(R.id.et_activity_register_tel);
        mNextButton = (TextView) findViewById(R.id.btn_activity_register);
        rl_activity_register_industory = (RelativeLayout) findViewById(R.id.rl_activity_register_industory);

    }

    @Override
    protected void initChildData() {
        mNextButton.setVisibility(canEdit ? View.VISIBLE : View.GONE);
        if (mShopId == 0) {
            return;
        }
        showLoadingDialog();
        ApiManager.getApi().searchShopInfo(
                "INV_HSY001010",
                mUserId
        ).enqueue(new NetCallBack<SearchShopBean>() {
            @Override
            protected void onSuccess(Call<SearchShopBean> call, Response<SearchShopBean> response) {
                BizShopBean bizShopBean = new BizShopBean();
                AuUserBean auUserBean = new AuUserBean();
                try {
                    bizShopBean = response.body().appBizShop;
                    auUserBean = response.body().appAuUser;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String cellphone = auUserBean.cellphone;
                String shopName = bizShopBean.name;
                industryCode = bizShopBean.industryCode;
                String industryName = bizShopBean.industryName;
                mShopNameView.setText(shopName);
                mSettleTypeView.setText(industryName);
                mTelView.setText(cellphone);
            }


            @Override
            protected boolean isNullNeedCallback() {
                return true;
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
        DoCanEdit(canEdit);

    }

    private void DoCanEdit(Boolean canEdit) {
        mShopNameView.setFocusable(canEdit);
        mShopNameView.setFocusableInTouchMode(canEdit);

        rl_activity_register_industory.setEnabled(canEdit);

        mTelView.setFocusable(canEdit);
        mTelView.setFocusableInTouchMode(canEdit);
        mNextButton.setVisibility(canEdit ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void setChildViewListener() {
        findViewById(R.id.rl_activity_register_industory).setOnClickListener(this);
        findViewById(R.id.btn_activity_register).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_activity_register:
                String shopName = mShopNameView.getText().toString();
                String tel = mTelView.getText().toString();

                String shopNameNew = stringFilter(shopName);

                if (TextUtils.isEmpty(shopName)) {
                    UIUtils.showToast("请填写店铺名称");
                    return;
                }
                if (shopName.length() < 5) {
                    UIUtils.showToast("店铺名称最少为5个字,请重新输入");
                    return;
                }
                if (shopName.length() > 25) {
                    UIUtils.showToast("店铺名称最多为25个字,请重新输入");
                    return;
                }
                if (!shopName.equals(shopNameNew)) {
                    UIUtils.showToast("店铺名称只能输入汉字,字母和数字,请重新输入");
                    return;
                }

                if (mDefaultIndex != -1) {
                    industryCode = TextUtils.isEmpty(industryCode) ? mSettleTypeList.get(mDefaultIndex).key : industryCode;
                }

                if (TextUtils.isEmpty(industryCode)) {
                    UIUtils.showToast("请选择所属行业");
                    return;
                }

                if (TextUtils.isEmpty(tel)) {
                    UIUtils.showToast("请填写手机号");
                    return;
                }

                if (tel.length() != 11) {
                    UIUtils.showToast("请填写正确的手机号");
                    return;
                }

                showLoadingDialog();
                ApiManager.getApi().reportRegister(
                        "INV_HSY001001",
                        tel,
                        shopName,
                        industryCode,
                        SharedPreferencesUtils.getLong(ConstantPool.REPORT_ACCOUT_ID, 0)
                ).enqueue(new NetCallBack<ReportRegisterGetBean>() {
                    @Override
                    protected void onSuccess(Call<ReportRegisterGetBean> call, Response<ReportRegisterGetBean> response) {
                        ReportRegisterGetBean reportRegisterGetBean = new ReportRegisterGetBean();
                        if (response != null && response.body() != null) {
                            reportRegisterGetBean = response.body();
                        }
                        long userId = 0;
                        if (reportRegisterGetBean.appAuUser != null) {
                            userId = reportRegisterGetBean.appAuUser.id;
                        }
                        long shopId = reportRegisterGetBean.appBizShop.id;
                        Bundle bundle = new Bundle();
                        bundle.putLong("report_account_id", userId);
                        bundle.putLong("report_shop_id", shopId);
                        ActivityUtils.startActivityAndFinish(RegisterAddActivity.this, IdentificationShopStep1Activity.class, bundle);
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                break;
            case R.id.rl_activity_register_industory:
                if (mSettleTypeList == null) {
                    showLoadingDialog();
                    ApiManager.getApi().getSettleType("INV_HSY001008").enqueue(new NetCallBack<List<KeyAndValueBean>>() {
                        @Override
                        protected void onSuccess(Call<List<KeyAndValueBean>> call, Response<List<KeyAndValueBean>> response) {
                            mSettleTypeList = response.body();

                            for (int i = 0; i < mSettleTypeList.size(); i++) {
                                mSettleTypeStringList.add(mSettleTypeList.get(i).value);
                            }

                            Bundle bundle = new Bundle();
                            bundle.putString(SelectListActivity.CENTER_TITLE, "所属行业");
                            bundle.putInt(SelectListActivity.DEFAULT_INDEX, mDefaultIndex);
                            bundle.putStringArrayList(SelectListActivity.DATA_LIST, mSettleTypeStringList);
                            ActivityUtils.startActivityForResult(RegisterAddActivity.this, SelectListActivity.class, bundle, REQUEST_CODE_SETTLE_TYPE);
                        }

                        @Override
                        protected void hiddenProgress() {
                            hideLodingDialog();
                        }
                    });
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString(SelectListActivity.CENTER_TITLE, "所属行业");
                    bundle.putInt(SelectListActivity.DEFAULT_INDEX, mDefaultIndex);
                    bundle.putStringArrayList(SelectListActivity.DATA_LIST, mSettleTypeStringList);
                    ActivityUtils.startActivityForResult(RegisterAddActivity.this, SelectListActivity.class, bundle, REQUEST_CODE_SETTLE_TYPE);
                }
                break;
//            case R.id.tv_activity_register_goto_login:
//                ActivityUtils.finishActivity(this);
//                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SETTLE_TYPE:
                    mDefaultIndex = data.getIntExtra("data", 0);
                    mSettleTypeView.setText(mSettleTypeList.get(mDefaultIndex).value);
                    break;
            }
        }
    }

    /**
     * 匹配正则表达式
     *
     * @param str
     * @return
     */
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字-
        //String   regEx  =  "[^a-zA-Z0-9-u4E00-u9FA5]";
        String regEx = "[^a-zA-Z0-9\u4e00-\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
}
